import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { Component, OnInit, Input, OnDestroy} from '@angular/core';

import { HttpService } from 'src/app/shared/service/http.service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { Subscription } from 'rxjs';
import { MessageService } from 'src/app/shared/service/message.service';
import { EventService } from 'src/app/shared/service/event.service';
import { ActionSheetService } from 'ng-zorro-antd-mobile';
import { ModalController, ActionSheetController, AlertController } from '@ionic/angular';
import { ServiceModuleComponent } from '../service-module/service-module.component';
import { SharePageComponent } from '../share-page/share-page.component';
import { RemarksContentComponent } from '../remarks-content/remarks-content.component';
import { RecommendModalComponent } from '../recommend-modal/recommend-modal.component';

@Component({
  selector: 'app-recommend-record-list',
  templateUrl: './recommend-record-list.component.html',
  styleUrls: ['./recommend-record-list.component.scss'],
})
export class RecommendRecordListComponent implements OnInit, OnDestroy {
  @Input() tagData: any;
  icons = [];
  dataIndex: any;
  openInformation = false;
  openRemarks = false;
  remarksText = "";
  remarksIcon: any;
  phoneArray = [];

  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  tempEvent: any;
   // 筛选及页面数据参数
  params: any = { content: {} };
  sessionId: string;
  // 声明订阅对象
  subscription: Subscription = null;
  listData: any;
  constructor(
    private appGlobalService: AppGlobalService,
    private httpService: HttpService,
    private message: MessageService,
    private actionSheet: ActionSheetService, // 必须有
    public modalController: ModalController,
    private actionSheetCtrl: ActionSheetController,
    private alertController: AlertController,
    private pageModalService: PageModalService
  ) { }

  ngOnInit() {
    // this.demoData();
    this.sessionId = localStorage.getItem('sessionId');
    if (this.tagData.data.submit !== undefined) {
        // 初始化参数
        this.params = this.tagData.data.submit;
        this.params.sessionId = this.sessionId;

        this.listData = this.tagData.data.data;
        this.pageSize = this.tagData.data.pageSize;
        this.pageTotal = this.tagData.data.pageTotal;
    }

    if (!this.subscription && this.tagData.data.submit !== undefined) {
      // 获取筛选参数
      this.subscription = this.message.getMessage().subscribe(param => {
          if (this.tempEvent) {
              this.tempEvent.target.disabled = false;
          }
          // // 重置当前页数
          this.pageNo = 1;
          // 参数
          if (!param) {
              return;
          }
          this.params.content = param;
          // 页面数据参数
          this.params.content.pageNo = this.pageNo;
          // 请求获取新数据
          this.httpService.post('application/submit', this.params, res => {
              // 请求数据成功
              if (res.success) {
                  const result = res.data.data; // JSON.parse(res.data.data);
                  // 筛选数据
                  this.tagData.data.data = result;
                  this.pageTotal = this.tagData.data.pageTotal;
                  this.listData = result;
              } else {
                  // 请求数据失败
                  this.appGlobalService.showToast(res.message, 2000, 'middle');
              }
          },
              err => {
                  // 请求数据失败
                  this.appGlobalService.showToast(err.message, 2000, 'middle');
              });
      });
  }
  }


  ngOnDestroy(): void {
    sessionStorage.removeItem('showName');
    if (this.tagData.data.submit !== undefined) {
        // 组件生命周期结束的时候，注销
        this.subscription.unsubscribe();
    }
}
  detailPage(link) {
    const pageParams = {
      pageId: link.target,
      params: link.params,
      sessionId: localStorage.getItem('sessionId')
    };
    this.appGlobalService.goToForward(pageParams);
  }

  call(phone) {
    this.httpService.changeCallNumber(phone);
  }

  loadMoreData(event) {
    try {
        this.tempEvent = event;
        // // 请求下一个页面
        this.pageNo = this.pageNo + 1;
        // // 参数
        this.params.content.pageNo = this.pageNo;
        // 请求获取新数据
        this.httpService.post('application/submit', this.params, res => {

            // 请求数据成功
            if (res.success) {
                const resList = res.data.data;
                // 追加返回数据
                if (resList && resList.length > 0) {
                    // 追加数据
                    resList.map(v => {
                        this.listData.push(v);
                    });
                } else {
                    event.target.disabled = true;
                }
            } else {
                // 请求失败，更新当前页数
                this.pageNo = this.pageNo - 1;
                // 请求数据失败
                this.appGlobalService.showToast(res.message, 2000, 'middle');
            }
            event.target.complete();

        }, err => {
            // 请求失败，更新当前页数
            this.pageNo = this.pageNo - 1;
            // 请求数据失败
            this.appGlobalService.showToast(err.message, 2000, 'middle');
            event.target.complete();

        });
    } catch (error) {
        console.log('error----->' + JSON.stringify(error));
    }
}
/**
   *
   * @param item 各种操作类型 icon 入口
   */
  iconClick(item) {
    this.hiddenInformation();
    // console.log(item);
    if (item.modelType === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {//
        this.httpService.gotoChat(item);
      } else if (item.label === '分享') {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          console.log(JSON.parse(res.script));
          const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
          // console.log(tmpShareData);
          this.presentShareModal(tmpShareData);
        });
      } else {
        // 修改
        const params = {
          pageId: item.link.target,
          params: item.link.params,
          sessionId: localStorage.getItem("sessionId")
        };
        this.appGlobalService.goToForward(params);
      }
    } else if (item.modelType === "iconSubmit") {
      // 领取
      const params = {
        // tslint:disable-next-line:max-line-length
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          // this.openInformation = false;
          // this.tagData.data.data[this.dataIndex] = res.data.data[0];
          if (item.link.target) {
            const pageParams = {
              pageId: item.link.target,
              params: item.link.params ? item.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    } else if (item.modelType === "phone") {
      // 电话
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), item.label);
      }
    } else if (item.modelType === "dialog") {
      // 备注
      // this.remarksIcon = item;
      // this.openRemarks = true;
      this.presentModal("remarks", item);
    } else
    // 新增两个components类型
    if (item.modelType === "remarkList") {
      if (item.listRemark) {
        this.remarkList(item);
      }
    } else if (item.modelType === "serviceModal") {
      this.openSeviceModal("sevice-modal", item);
    } else if (item.modelType === "popupDiv") {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, res => {
        this.pageModalService.getPageTagDataWithPageRes(res,  data => {
          this.showRecommenMessage(data);
        });
      });
    } else if (item.modelType === "alertSubmit") {
        this.presentAlertSubmit(item);
      }
  }
    /**
   *
   * @param item 打开图标
   */
  openIcon(item) {
    this.icons = item.slice(3);
    this.showActionSheet(this.icons);
  }

  showActionSheet(icons) {
    const that = this;
    const buttons: any = [];
    icons.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(icons[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.iconClick(icons[buttonIndex]);
          }, 200);
        }
      }
    );
  }

  async openSeviceModal(className, item) {
    const type = {
      "sevice-modal": ServiceModuleComponent,
    };
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: className,
      component: type[className],
      componentProps: { tagData: item }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }

  /**
   * 关闭图标
   */
  hiddenInformation() {
    this.openInformation = false;
    this.openRemarks = false;
  }

  // 分享弹框
  async presentShareModal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }

  async presentAction() {
    const buttonsArr = [
      {
        text: "取消",
        cssClass: ["action-sheet-font-color", "action-sheet-font-top"],
        handler: () => {
          actionSheet.dismiss();
        }
      }
    ];
    if (this.phoneArray[1]) {
      buttonsArr.unshift({
        text: this.phoneArray[1],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(Number(this.phoneArray[1]));
        }
      });
    }

    if (this.phoneArray[0]) {
      buttonsArr.unshift({
        text: this.phoneArray[0],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[0]);
        }
      });
    }

    const actionSheet = await this.actionSheetCtrl.create({
      mode: "md",
      cssClass: "match-padding",
      buttons: buttonsArr
    });
    await actionSheet.present();
  }

  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }

  /**
   * 提交备注
   */
  submitRemarks() {
    if (this.remarksText === "") {
      this.appGlobalService.showToast("请填写备注", 1000, "top");
      return;
    }
    const contentArray = this.remarksIcon.formData.button.submit.content;
    // tslint:disable-next-line:no-string-literal
    contentArray["remark_text"] = this.remarksText;
    const params = {
      content: contentArray,
      id: this.remarksIcon.formData.button.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        this.remarksText = "";
        this.openRemarks = false;
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      } else {
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      }
    });
  }

  async presentModal(value, item) {
    console.log("item", item);
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: value,
      component: RemarksContentComponent,
      componentProps: { item, type: value }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
  }


  remarkList(more) {
    const that = this;
    const buttons: any = [];
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex);
          }, 200);
        }
      }
    );
  }

  selectItem(item, index) {
    const itemObj = item.listRemark[index];
    if (itemObj.modelType === 'dialog') {
      this.presentModal("remarks", itemObj);
    } else if (itemObj.modelType === 'iconLink') {
      // 修改 领取类型按钮
      const params = {
        pageId: itemObj.link.target,
        params: itemObj.link.params,
        sessionId: localStorage.getItem("sessionId")
      };
      this.appGlobalService.goToForward(params);
    } else if (itemObj.modelType === 'phone') {
      // 电话
      this.phoneArray = itemObj.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), itemObj.label);
      }
    } else if (itemObj.modelType === 'iconSubmit') {
      // 领取
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (itemObj.link.target) {
            const pageParams = {
              pageId: itemObj.link.target,
              params: itemObj.link.params ? itemObj.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    } else if (itemObj.modelType === 'popupDiv') {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, res => {
        this.pageModalService.getPageTagDataWithPageRes(res,  data => {
          this.showRecommenMessage(data);
        });
      });
    } else if (itemObj.modelType === 'alertSubmit') {
        this.presentAlertSubmit(itemObj);
    }
  }

// 推荐语
 async showRecommenMessage(tagData) {
    const modal = await this.modalController.create({
        showBackdrop: true,
        cssClass: 'recommend-modal',
        component: RecommendModalComponent,
        componentProps: { tagData }
      });
      await modal.present();
      // 监听销毁的事件
      const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
 }
    
  // 二次确认短信
  async presentAlertSubmit(data) {
    
    const alert = await this.alertController.create({
      header: data.label,
      message: data.alert,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            const params = {
                content: data.submit.content,
                id: data.submit.id,
                sessionId: localStorage.getItem("sessionId")
              };
            this.submit(params);
          }
        }
      ]
    });

    await alert.present();
  }

  submit(params) {
      this.httpService.post("application/submit", params, res => {
        if (res.message) {
            this.appGlobalService.showToast(res.message, 1500, "middle");
        }
     });
  }
}
